import java.util.HashSet;

public class SetApplication {
    public static void main(String[] args) {
        HashSet<MyUser> set = new HashSet<MyUser>();
        MyUser u1 = new MyUser("Tom", 25);
        MyUser u2 = new MyUser("Bob", 18);
        set.add(u1);
        set.add(u2);

        u1.name = "Tommy";
        // set.remove底层先调用hashCode()方法，再调用equals()方法
        // hashCode方法已经判断当前对象不在同一个位置，所以不会调用equals方法
        set.remove(u1);
        System.out.println(set); // [18 Bob, 25 Tom]

        set.add(new MyUser("Tom", 25)); // [18 Bob, 25 Tom, 25 Tom]
        System.out.println(set);

        set.add(new MyUser("Tom", 25)); // [18 Bob, 25 Tom, 25 Tom]
        System.out.println(set);

    }
}

class MyUser {
    String name;
    int age;

    MyUser(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String toString() {
        return age + " " + name;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o)
            return true;
        if (!(o instanceof MyUser))
            return false;
        MyUser myUser = (MyUser) o;
        return age == myUser.age && name.equals(myUser.name);
    }

    @Override
    public int hashCode() {
        System.out.println("hashcode call me");
        System.out.println("name: " + name + " hashcode: " + name.hashCode() + " age: " + age);
        return name.hashCode() + age;
    }
}
